package com.lastproject.web.bean;

import java.util.Arrays;
import java.util.Comparator;

import javax.faces.model.DataModel;
import javax.faces.model.DataModelListener;

public class BookFilterModel extends DataModel<BookBean> {

	private DataModel<BookBean> model;
	private Row[] rows;

	private static Comparator<Row> byName = new Comparator<Row>() {
		public int compare(Row r1, Row r2) {
			BookBean b1 = (BookBean) r1.getData();
			BookBean b2 = (BookBean) r2.getData();
			return b1.getBook().getName().compareTo(b2.getBook().getName());
		}
	};

	private static Comparator<Row> byAuthor = new Comparator<Row>() {
		public int compare(Row r1, Row r2) {
			BookBean b1 = (BookBean) r1.getData();
			BookBean b2 = (BookBean) r2.getData();
			return b1.getBook().getAuthor().compareTo(b2.getBook().getAuthor());
		}
	};

	public class Row {
		private int row;

		public Row(int row) {
			this.row = row;
		}

		public Object getData() {
			int originalIndex = model.getRowIndex();
			model.setRowIndex(row);
			Object thisRowData = model.getRowData();
			model.setRowIndex(originalIndex);
			return thisRowData;
		}
	}

	public BookFilterModel() {
		this((BookBean[]) null);
	}

	public BookFilterModel(BookBean[] books) {
		setWrappedData(books);
	}

	public BookFilterModel(DataModel<BookBean> model) {
		this.model = model;
		initializeRows();
	}

	public void setRowIndex(int rowIndex) {
		if (rowIndex == -1 || rowIndex >= model.getRowCount()) {
			model.setRowIndex(rowIndex);
		} else {
			model.setRowIndex(rows[rowIndex].row);
		}
	}

	public boolean isRowAvailable() {
		return model.isRowAvailable();
	}

	public int getRowCount() {
		return model.getRowCount();
	}

	public BookBean getRowData() {
		return model.getRowData();
	}

	public int getRowIndex() {
		return model.getRowIndex();
	}

	public Object getWrappedData() {
		return model.getWrappedData();
	}

	public void setWrappedData(Object data) {
		model.setWrappedData(data);
		initializeRows();
	}

	public void addDataModelListener(DataModelListener listener) {
		model.addDataModelListener(listener);
	}

	public DataModelListener[] getDataListeners() {
		return model.getDataModelListeners();
	}

	public void removeDataModelListener(DataModelListener listener) {
		model.removeDataModelListener(listener);
	}

	public void initializeRows() {
		int rowCnt = model.getRowCount();
		if (rowCnt != -1) {
			rows = new Row[rowCnt];
			for (int i = 0; i < rowCnt; i++) {
				rows[i] = new Row(i);
			}
		}
	}

	public String sortByAuthor() {
		Arrays.sort(rows, byAuthor);
		return null;
	}

	public String sortByName() {
		Arrays.sort(rows, byName);
		return null;
	}
}
